package com.aube.plugin.rank.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by huyaonan on 16/8/11.
 */
public class FixedSizeImageView extends ImageView {

    private int sizeW=0;
    private int sizeH=0;

    public FixedSizeImageView(Context context) {
        this(context, null);
    }

    public FixedSizeImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FixedSizeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(sizeH > 0 && sizeW > 0) {
            int measureWidth = measureWidth(widthMeasureSpec);
            int measureHeight = measureHeight(heightMeasureSpec);

            if(measureWidth > 0 && measureHeight == 0) {
                measureHeight = measureWidth * sizeH / sizeW;
                setMeasuredDimension(measureWidth, measureHeight);
            }
        }
    }

    private int measureWidth(int pWidthMeasureSpec) {
        int result = 0;
        int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式
        int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸

        switch (widthMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = widthSize;
                break;
        }
        return result;
    }

    private int measureHeight(int pHeightMeasureSpec) {
        int result = 0;

        int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);

        switch (heightMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = heightSize;
                break;
        }
        return result;
    }

    public void updateSize(int w, int h) {
        if(w > 0 && h > 0) {
            sizeW = w;
            sizeH = h;
            requestLayout();
        }
    }

}
